import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, ScrollView, TouchableOpacity, Dimensions, TextInput, Modal, ActivityIndicator,Alert } from "react-native";
import { style } from '../../theme/style';
import { Common } from '../../component/common/Common';
import ToastUtil from '../../utils/toast';
import PasswordGesture from 'react-native-gesture-password';
import { PageStatusIndex } from '../../component/page-status/PageStatusIndex';
import { GLOBAL } from '../../config/global';
import StorageHelper from '../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../config/storage';
import HTTP from '../../utils/http';
import { API, API_GENERATE } from '../../config/api';
import * as Keychain from 'react-native-keychain';
import Dictionary from '../../utils/dictionary';
import Permission from '../../utils/permission';
const appInfo = require('react-native-device-info');
const logoIcon = require('../../imgs/logoIng.png');
const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;
const ScreenHeight = Dimensions.get('window').height;

export class gestureLogin extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      header:null,
    }
  }

  constructor(props) {
    super(props);
    this.state = {
      message:'',
      wordStatus:'normal'
    };
    this.loginInfo = {
			loginName: '',
			password: ''
		}
  }

  async	componentWillMount () {
    this._init();
  }

  //初始函数
  _init = async () => {
    GLOBAL.BIND_GESTURE_PASSWORD = await StorageHelper.get(STORAGE_CONSTANT.BIND_GESTURE_PASSWORD);
    // console.log(this.props.navigation.state)
  }
  // 登录
  async login () {
    if (this.requesting) return;
    this.loginInfo.devCode = appInfo.getUniqueID();
    this.setState({
      status: 'loading'
    })
    this.requesting = true;
    let { params } = this.props.navigation.state;
    if(params.username&&params.password){
      this.loginInfo.loginName = params.username;
      this.loginInfo.password = params.password;
    }
    else{
      await Keychain.getGenericPassword().then(credentials => {
        this.loginInfo.loginName = credentials.username;
        this.loginInfo.password = credentials.password;
      })
    }
    let loginResult = await HTTP.POST(API_GENERATE(API.DO_LOGIN), this.loginInfo);
    if (loginResult) {
      if (loginResult.pwdReset === 1) {
        GLOBAL.pwdReset = true;
        this.requesting = false;
        this.props.navigation.navigate('SetPassWordPage', { resetPwdToken: loginResult.token, pwdReset: true });
      } else {
        let userInfo = loginResult;
        await this.saveUserInfo(userInfo);
      }
    } else {
      this.requesting = false;
    }
    this.setState({
      status: 'data'
    })
  }

  async saveUserInfo (userInfo) {
    GLOBAL.TOKEN = userInfo.authToken;
    GLOBAL.LOGIN_NAME = userInfo.loginName;
    this._registerJPush();
    Promise.all([
      Dictionary.init(),
      Permission.init(),
      StorageHelper.multiSet([
        [STORAGE_CONSTANT.USER_INFO_KEY, userInfo],
        [STORAGE_CONSTANT.TOKEN, userInfo.authToken],
        [STORAGE_CONSTANT.LOGIN_ACCOUNT_KEY, this.loginInfo.loginName],
      ])
    ]).then(() => {
      ToastUtil.showSuccess('登录成功').then(async () => {
        GLOBAL.BIND_LOGIN_TYPE = 'GESTURE'
        StorageHelper.set(STORAGE_CONSTANT.BIND_LOGIN_TYPE, GLOBAL.BIND_LOGIN_TYPE);
        GLOBAL.CURR_MODULE = '2.0';
        this.requesting = false;
        this.props.navigation.navigate('Layout');
      })
    })
  }

  async _registerJPush () {
    let APP_HOT_VERSION = await StorageHelper.get(STORAGE_CONSTANT.APP_HOT_VERSION);
    //极光推送
    if (!appInfo.isEmulator()) {
      let registrationId = await StorageHelper.get(STORAGE_CONSTANT.REGISTRATION_ID);
      await HTTP.POST(API_GENERATE(API.PUSH_REGISTER_INFO), {
        appVersion: appInfo.getVersion(),
        deviceCode: appInfo.getUniqueID(),
        deviceType: Platform.OS.substring(0, 1),
        osVersion: appInfo.getSystemVersion(),
        phoneBrand: appInfo.getModel(),
        phoneModel: appInfo.getModel(),
        registrationId: registrationId,
        extVersionCode: APP_HOT_VERSION
      });
    }
  }

  onEnd=(password) =>{
    if (password == GLOBAL.BIND_GESTURE_PASSWORD) {
        ToastUtil.showSuccess('密码正确').then(() => {
          this.login()
      })
    } else {
        this.setState({
            wordStatus: 'wrong',
            message: '密码错误，请再次尝试'
        });
    }
    }
    onStart= () =>{
        this.setState({
          wordStatus: 'normal',
            message: ''
        });
    }
  logout () {
    GLOBAL.BIND_GESTURE_PASSWORD = ''
    StorageHelper.set(STORAGE_CONSTANT.BIND_GESTURE_PASSWORD, GLOBAL.BIND_GESTURE_PASSWORD);
    if(GLOBAL.BIND_BIOMETRY_AUTH){
      GLOBAL.BIND_LOGIN_TYPE = 'BIOMETRY'
    }
    else{
      GLOBAL.BIND_LOGIN_TYPE = ''
    }
    StorageHelper.set(STORAGE_CONSTANT.BIND_LOGIN_TYPE, GLOBAL.BIND_LOGIN_TYPE);
    if(this.props.navigation.state.params.refreshData){
      this.props.navigation.state.params.refreshData();
    }
    this.props.navigation.navigate('LoginPage')
  }
  render () {
    let color
    if(this.state.wordStatus === 'wrong'){
      color =  '#D93609'
    }
    else if(this.state.wordStatus === 'right'){
      color =  '#5FA8FC'
    }
    else{
      color =  '#5FA8FC'
    }
    let {wordStatus,message,status} = this.state
    return (
      <View style={{ flex: 1 }}>
        <View style={styles.itemBox}>
          <Image style={styles.itemBoxIcon} source={logoIcon} />
        </View>
        <View style={styles.messageStyle}>
          <Text style={[styles.messageText, { color: color }]}>{message}</Text>
        </View>
        <View style={{ height: 550 * scale,marginTop:35*scale  }}>
            <PasswordGesture
              style={{ backgroundColor: '#fff' }}
              ref='pg'
              status={wordStatus}
              // message={message}
              onStart={() => this.onStart()}
              onEnd={(password) => this.onEnd(password)}
              interval={1000}
            />
        </View>
        <View style={styles.bottom}>
          <TouchableOpacity  style={styles.bottomBox} onPress={() => { Alert.alert('提示', '忘记手势，可以使用其他登陆方式，同时原手势密码失效', [
                { text: '取消' },
                {
                  text: '其他登陆方式', onPress: async () => {
                    this.logout()
                  }
                },
              ]);}}>
              <Text style={styles.bottomText}>忘记手势？| </Text>
          </TouchableOpacity>
          <TouchableOpacity  style={styles.bottomBox} onPress={() => {this.props.navigation.navigate('LoginPage')}}>
              <Text style={styles.bottomText}> 登入其他账号</Text>
          </TouchableOpacity>
        </View>
        {
					status == 'loading' ? (<View style={{ position: 'absolute', height: ScreenHeight, width: ScreenWidth, top: 0 }}>
						<PageStatusIndex status={status} />
					</View>
					) : null
				}
        
      </View>   
    )
  }
}


const styles = StyleSheet.create({
  itemBox: {
    flexDirection: 'row',
    justifyContent: 'center',
    paddingTop: 30 * scale,
    width:'100%',
    position: "absolute",
    top: 0*scale,
    zIndex: 9*scale,
    backgroundColor:'#fff'
    // paddingBottom: 110 * scale,
  },
  itemBoxIcon: {
    width: 120 * scale,
    height: 120 * scale,
  },
  messageStyle: {
    width:'100%',
    // marginTop: 30 * scale,
    justifyContent: 'center',
    alignItems: 'center',
    position: "absolute",
    top: 160*scale,
    zIndex: 9*scale
  },
  messageText: {
    color: '#5FA8FC',
    fontSize: 14 * scale
  },
  rightBox: {
    width: 50 * scale,
    justifyContent: 'center',
    alignItems: 'center'
  },
  rightText: {
    color: '#fff',
    fontSize: 14 * scale
  },
  closeBox:{
    // backgroundColor:'red',
    marginTop:250*scale
  },
  itemText: {
    flexDirection: 'row',
    justifyContent: 'center',
    paddingTop: 40 * scale,
  },
  itemTitle: {
    fontSize: 16 * scale,
    color: '#000',
  },
  flexText: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 100 * scale,
    alignItems: 'center',
  },
  itemCtn: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 66 * scale,
    marginLeft: 20 * scale,
    marginRight: 20 * scale,
    paddingBottom: 20 * scale,
    paddingTop: 20 * scale,
    backgroundColor: '#0E7FFD',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: '#0E7FFD',
    borderRadius: 5 * scale,
  },
  itemBtn: {
    fontSize: 16 * scale,
    color: '#fff',
  },
  bottom:{
    marginTop:30*scale,
    justifyContent:"center",
    alignItems:'center',
    flexDirection:"row"
  },
  bottomBox:{
    justifyContent:"center",
    alignItems:'center',
  },
  bottomText:{
    color:'#0087FF',
  }
})